#!/usr/bin/env python
# -*- coding: utf-8 -*-

import redis
import cPickle
import os
import time
import tornado.httpclient
import json
import tempfile
# redis config
pool = redis.ConnectionPool(host='127.0.0.1', port=6379, db=0)
r = redis.Redis(connection_pool=pool)

def get_ranks():
    """run"""
    # var
    ranks = list()
    avatars = list()
    # temp = tempfile.mkdtemp(suffix='_py', prefix='_python_')
    temp = tempfile.gettempdir()
    rank_cache = r"rank"
    rank_cache = os.path.join(temp, '%s.txt' % rank_cache)
    rank_key = "fuwa_rank"
    rank_num = 100
    # get data from redis
    for rank in r.zrevrange(rank_key, 0, rank_num-1, withscores=True):
        avatars.append(rank[0])
    url = r'https://api.66boss.com/ucenter/userinfo/nick?avatar=1&user_id=%s' % (','.join(avatars))
    c = tornado.httpclient.HTTPClient()
    try:
        res = c.fetch(url)
        c.close()
        t = json.loads(res.body)
    except tornado.httpclient.HTTPError as e:
        print 'err: %s' % e
        return
    if t['result']:
        avatars = t['result']
    # merge
    for rank in r.zrevrange(rank_key, 0, rank_num-1, withscores=True):
        t = rank + (avatars.get(rank[0])[0], avatars.get(rank[0])[1])
        ranks.append(t)
    # write cache
    with open(rank_cache, "w") as fp:
        cPickle.dump(ranks, fp)
    # return data
    return ranks

if __name__ == "__main__":
    while not get_ranks():
        print r"get ranks failure, 50s again get it"
        time.sleep(50)
